﻿namespace SmartMD.Manager.Controls
{
    using System.Windows;
    using System.Windows.Media;

    public static class ListViewHelper
    {
        /// <summary>
        /// Okay, I know this methods cause stack overflow.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="element"></param>
        /// <returns></returns>
        public static T FindAncestor<T>(this DependencyObject element)
            where T : DependencyObject
        {
            if (element == null)
            {
                return null;
            }

            DependencyObject ancestor = VisualTreeHelper.GetParent(element);

            if (element is FrameworkElement)
            {
                ancestor = ancestor ?? ((element as FrameworkElement).Parent ?? (element as FrameworkElement).TemplatedParent);
            }

            //While, I expend CSharp compiler could handle  尾递归。
            return ancestor is T ? ancestor as T : FindAncestor<T>(ancestor);
        }
    }
}
